package com.mdhw.system.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.mdhw.common.contants.CacheKeyContants;
import com.mdhw.system.service.WechatAppletService;
import com.mdhw.utils.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dingzhj
 * @version 1.0.0
 * @ClassName WeChatAppletService.java
 * @Description TODO
 * @createTime 2022年08月12日 11:16:00
 */
@Slf4j
@Service
public class WeChatAppletServiceImpl implements WechatAppletService {


    @Value("${wx.miniapp.envVersion}")
    private String envVersion;

    @Value("${wx.miniapp.path}")
    private String path;

    @Value("${wx.miniapp.wxUrl}")
    private String wxUrl;

    @Value("${wx.miniapp.tokenUrl}")
    private String tokenUrl;

    @Value("${wx.miniapp.appid}")
    private String appid;

    @Value("${wx.miniapp.secret}")
    private String secret;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AliYunOssServer aliYunOssServer;


    /**
     * TODO 小程序上线天调试
     * 获取 openlink
     * @param
     * @return
     */
   /* public String openlink(PopularizeVo popularizeVo) {
        String activeProfile = SpringUtil.getActiveProfile();
        try{
            String isDev = "prod".equals(activeProfile) ? "0" : "1";
            JSONObject object = new JSONObject();
            JSONObject jumpWxa = new JSONObject();
            log.info("当前环境:{} isDev : {}",activeProfile,isDev);
            jumpWxa.put("path",path);
            String query = String.format("onlyCode=%s&orderId=%d&isDev=%s",popularizeVo.getOnlyCode(),popularizeVo.getOrderId(),isDev);
            jumpWxa.put("query",query);
            Long time =(System.currentTimeMillis()/1000)+7200;
            object.put("expire_time",time);
            //develop
            jumpWxa.put("env_version",envVersion);
            object.put("jump_wxa",jumpWxa);
            log.info("[微信小程序] openlink 请求参数: {}",object.toString());
            String url = wxUrl+this.getToken();
            String req = OkHttpUtil.getInstance().postJson(url,object.toString());
            log.info("[微信小程序] openlink: {}",req);
            JSONObject jsonObject = new JSONObject(req);
            Integer errcode = jsonObject.getInt("errcode");
            if(errcode == 0){
                return jsonObject.getString("openlink");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }
*/
    /*public String openlinkWithAppIdServret(PopularizeVo popularizeVo, MhTuiaPayConfig mhTuiaPayConfig,String path) {
        String activeProfile = SpringUtil.getActiveProfile();
        try{
            MhPopularizePayConfig mhPopularizePayConfig = popularizeVo.getMhPopularizePayConfig();
            String isDev = "prod".equals(activeProfile) ? "0" : "1";
            JSONObject object = new JSONObject();
            JSONObject jumpWxa = new JSONObject();
            log.info("当前环境:{} isDev : {}",activeProfile,isDev);
            if(!StringUtil.isBlank(path)){
                jumpWxa.put("path",path);
            }else{
                jumpWxa.put("path",this.path);
            }
            String payType = mhTuiaPayConfig.getPayType();
            String query = String.format("onlyCode=%s&orderId=%d&isDev=%s&appType=%s",popularizeVo.getOnlyCode(),popularizeVo.getOrderId(),isDev,"1");
            jumpWxa.put("query",query);
            Long time =(System.currentTimeMillis()/1000)+7200;
            object.put("expire_time",time);
            //develop
            jumpWxa.put("env_version",envVersion);
            object.put("jump_wxa",jumpWxa);
            log.info("[微信小程序] openlink 请求参数: {}",object.toString());
            String appid = mhTuiaPayConfig.getAppid();
            String secret = mhTuiaPayConfig.getRemark2();
            if(PopularizeEnum.PAY_TYPE_16.getCode().equals(payType)){
                secret = mhTuiaPayConfig.getPayKey();
            }
            if(PopularizeEnum.PAY_TYPE_18.getCode().equals(payType) || PopularizeEnum.PAY_TYPE_28.getCode().equals(payType)){
                String remark2 = mhTuiaPayConfig.getRemark2();
                if(!StringUtil.isBlank(remark2)){
                    com.alibaba.fastjson.JSONObject remarkJson = com.alibaba.fastjson.JSONObject.parseObject(remark2);
                    appid = remarkJson.getString("appid");
                    secret = remarkJson.getString("secret");
                }
            }
            String url ="";
            if(!StringUtil.isBlank(appid) && !StringUtil.isBlank(secret)){
                url = wxUrl+this.getTokenWithAppidSecret(appid,secret);
            }else{
                url = wxUrl+this.getToken();
            }

            String req = OkHttpUtil.getInstance().postJson(url,object.toString());
            log.info("[微信小程序] openlink: {}",req);
            JSONObject jsonObject = new JSONObject(req);
            Integer errcode = jsonObject.getInt("errcode");
            if(errcode == 0){
                return jsonObject.getString("openlink");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }*/
    public String openlinkWithAppIdServret(String appid,String secret,String path,String yaoqingma) {
        String activeProfile = SpringUtil.getActiveProfile();
        try{
            String isDev = "prod".equals(activeProfile) ? "0" : "1";
            JSONObject object = new JSONObject();
            JSONObject jumpWxa = new JSONObject();

            if(!StringUtils.isBlank(path)){
                jumpWxa.put("path",path);
            }else{
                jumpWxa.put("path",this.path);
            }

            //String query = String.format("onlyCode=%s&orderId=%d&isDev=%s&appType=%s",popularizeVo.getOnlyCode(),popularizeVo.getOrderId(),isDev,"1");
            String query = String.format("yaoqingma=%s",yaoqingma);
            jumpWxa.put("query",query);
            Long time =(System.currentTimeMillis()/1000)+7200;
            object.put("expire_time",time);
            //develop
            jumpWxa.put("env_version",this.envVersion);
            object.put("jump_wxa",jumpWxa);


            String url ="";
            if(!StringUtils.isBlank(appid) && !StringUtils.isBlank(secret)){
                url = wxUrl+this.getTokenWithAppidSecret(appid,secret);
            }
            String req = OkHttpUtil.getInstance().postJson(url,object.toString());
            JSONObject jsonObject = JSONObject.parseObject(req);
            Integer errcode = jsonObject.getInteger("errcode");
            if(errcode == 0){
                log.info("[微信小程序跳转 ] : openLink : {}",jsonObject.getString("openlink"));
                return jsonObject.getString("openlink");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

    public String getUnlimitedQRCode(String appid,String secret,String path,String yaoqingma){
        Date nowTime = new Date();
        String accessToken = this.getTokenWithAppidSecret(appid, secret);
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;

        Map<String,Object> params = new HashMap<>();
       // params.put("access_token",accessToken);
        params.put("scene","yaoqingma="+yaoqingma);
        params.put("page",path);
        params.put("check_path",Boolean.TRUE);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(url, JSONObject.toJSONString(params), byte[].class);
        byte[] body = responseEntity.getBody();
        assert body != null;
        InputStream byteArrayInputStream = new ByteArrayInputStream(body);
        AliYunOssResult upload = this.aliYunOssServer.upload(byteArrayInputStream,"jiazhuangQrCode/" + DateUtil.formatDate(nowTime, DateUtil.yyyy_mm_dd_hh_mm_ss) + "__" + yaoqingma + ".PNG");
        String qrCodeUrl = upload.getUrl();
        return qrCodeUrl;
    }


    /**
     * 获取用户openId
     * @param code
     * @return
     */
   /* public String openId(String code) {
        try{
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
            Response response =  OkHttpUtil.getInstance().getData(url);
            String res = response.body().string();
            log.info("获取openID返回参数 {}",res);
            JSONObject jsonObject = new JSONObject(res);
            return  jsonObject.getString("openid");
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }*/

    /**
     * 获取用户openIdWithAddidSecret
     * @param code
     * @return
     */
   /* public String openIdWithAddidSecret(String code,String appid,String secret) {
        try{
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
            Response response =  OkHttpUtil.getInstance().getData(url);
            String res = response.body().string();
            log.info("获取openID返回参数 {}",res);
            JSONObject jsonObject = new JSONObject(res);
            return  jsonObject.getString("openid");
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }*/

    /**
     * 获取token
     * @return
     */
    /*public String getToken() {
        String key = CacheKeyConst.WX_MINI_GET_TOKEN_KEY + appid+":"+secret;
        String accessToken = (String) this.redisUtil.get(key);
        if(!StringUtil.isBlank(accessToken)){
            log.info("[微信小程序] 缓存 获取accessToken: {}",accessToken);
            return accessToken;
        }
        try{
            String getTokenurl = tokenUrl+"&appid="+appid+"&secret="+secret;
            Response response =  OkHttpUtil.getInstance().getData(getTokenurl);
            if(response.code() == 200){
                String res = response.body().string();
                log.info("[微信小程序] 获取accessToken: {}",res);
                JSONObject jsonObject = new JSONObject(res);
                accessToken =  jsonObject.getString("access_token");
                Integer expireIn = jsonObject.getInt("expires_in");
                this.redisUtil.setIfAbsent(key,accessToken,expireIn);
                return accessToken;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }*/

    /**
     * 获取token
     * @return
     */
    public String getTokenWithAppidSecret(String appid,String secret) {

        String key = CacheKeyContants.WX_MINI_GET_TOKEN_KEY + appid+":"+secret;
        String accessToken = (String) this.redisUtil.get(key);
        if(!StringUtils.isBlank(accessToken)){
            log.info("[微信小程序] 缓存 获取accessToken: {}",accessToken);
            return accessToken;
        }
        try{
            String getTokenurl = tokenUrl+"&appid="+appid+"&secret="+secret;
            log.info("[微信小程序] 获取accessToken 参数 :  {}",getTokenurl);
            Response response =  OkHttpUtil.getInstance().getData(getTokenurl);
            if(response.code() == 200){
                String res = response.body().string();
                log.info("[微信小程序] 获取accessToken: {}",res);
                JSONObject jsonObject = JSONObject.parseObject(res);
                accessToken =  jsonObject.getString("access_token");
                Integer expireIn = jsonObject.getInteger("expires_in");
                this.redisUtil.setIfAbsent(key,accessToken,expireIn);
                return accessToken;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }


}
